#!/bin/bash

# DevOps SmartBot 健康检查脚本
# 用途: 检查所有服务的运行状态

echo "🏥 DevOps SmartBot - Health Check"
echo "=================================="

# 颜色定义
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# 检查函数
check_service() {
    local name=$1
    local url=$2
    local expect_code=${3:-200}

    response=$(curl -s -o /dev/null -w "%{http_code}" "$url" 2>&1)

    if [ "$response" -eq "$expect_code" ]; then
        echo -e "${GREEN}✓${NC} $name - OK"
        return 0
    else
        echo -e "${RED}✗${NC} $name - FAILED (HTTP $response)"
        return 1
    fi
}

# 检查Docker容器
check_docker() {
    local container=$1
    local name=$2

    if docker ps | grep -q "$container"; then
        echo -e "${GREEN}✓${NC} $name - RUNNING"
        return 0
    else
        echo -e "${RED}✗${NC} $name - NOT RUNNING"
        return 1
    fi
}

# 检查进程
check_process() {
    local pid_file=$1
    local name=$2

    if [ -f "$pid_file" ]; then
        pid=$(cat "$pid_file")
        if ps -p $pid > /dev/null 2>&1; then
            echo -e "${GREEN}✓${NC} $name - RUNNING (PID: $pid)"
            return 0
        else
            echo -e "${RED}✗${NC} $name - DEAD (PID file exists but process not found)"
            return 1
        fi
    else
        echo -e "${YELLOW}⚠${NC} $name - NOT STARTED (no PID file)"
        return 1
    fi
}

total_checks=0
passed_checks=0

echo -e "\n📊 应用服务:"
echo "─────────────────────────────"

# 前端
check_service "Frontend (Vue)" "http://localhost:3000" && ((passed_checks++))
((total_checks++))

# 后端API
check_service "Backend API" "http://localhost:8000/health" && ((passed_checks++))
((total_checks++))

# Prometheus
check_service "Prometheus" "http://localhost:9090/-/healthy" && ((passed_checks++))
((total_checks++))

# Alertmanager
check_service "Alertmanager" "http://localhost:9093/-/healthy" && ((passed_checks++))
((total_checks++))

# Grafana
check_service "Grafana" "http://localhost:3001" 302 && ((passed_checks++))
((total_checks++))

echo -e "\n🐳 Docker 容器:"
echo "─────────────────────────────"

# MongoDB
check_docker "devops-mongodb" "MongoDB" && ((passed_checks++))
((total_checks++))

# Redis
check_docker "devops-redis" "Redis" && ((passed_checks++))
((total_checks++))

# Node Exporter
check_docker "devops-node-exporter" "Node Exporter" && ((passed_checks++))
((total_checks++))

# Redis Exporter
check_docker "devops-redis-exporter" "Redis Exporter" && ((passed_checks++))
((total_checks++))

# MongoDB Exporter
check_docker "devops-mongodb-exporter" "MongoDB Exporter" && ((passed_checks++))
((total_checks++))

echo -e "\n🔌 API 端点测试:"
echo "─────────────────────────────"

# 测试后端API端点
if curl -s http://localhost:8000/api/alerts > /dev/null 2>&1; then
    echo -e "${GREEN}✓${NC} GET /api/alerts"
    ((passed_checks++))
else
    echo -e "${RED}✗${NC} GET /api/alerts"
fi
((total_checks++))

if curl -s http://localhost:8000/api/alerts/statistics > /dev/null 2>&1; then
    echo -e "${GREEN}✓${NC} GET /api/alerts/statistics"
    ((passed_checks++))
else
    echo -e "${RED}✗${NC} GET /api/alerts/statistics"
fi
((total_checks++))

if curl -s http://localhost:8000/api/prometheus/status > /dev/null 2>&1; then
    echo -e "${GREEN}✓${NC} GET /api/prometheus/status"
    ((passed_checks++))
else
    echo -e "${RED}✗${NC} GET /api/prometheus/status"
fi
((total_checks++))

# 测试Prometheus查询
if curl -s "http://localhost:9090/api/v1/query?query=up" > /dev/null 2>&1; then
    echo -e "${GREEN}✓${NC} Prometheus Query API"
    ((passed_checks++))
else
    echo -e "${RED}✗${NC} Prometheus Query API"
fi
((total_checks++))

# 测试Alertmanager API
if curl -s http://localhost:9093/api/v1/alerts > /dev/null 2>&1; then
    echo -e "${GREEN}✓${NC} Alertmanager API"
    ((passed_checks++))
else
    echo -e "${RED}✗${NC} Alertmanager API"
fi
((total_checks++))

echo -e "\n📈 监控数据:"
echo "─────────────────────────────"

# 获取活跃告警数量
alert_count=$(curl -s http://localhost:9093/api/v1/alerts 2>/dev/null | grep -o '"status":"firing"' | wc -l)
echo "  活跃告警数量: $alert_count"

# 获取Prometheus targets状态
targets_up=$(curl -s http://localhost:9090/api/v1/targets 2>/dev/null | grep -o '"health":"up"' | wc -l)
targets_total=$(curl -s http://localhost:9090/api/v1/targets 2>/dev/null | grep -o '"health"' | wc -l)
echo "  Prometheus Targets: $targets_up/$targets_total UP"

echo -e "\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo -e "总体健康度: ${passed_checks}/${total_checks} 检查通过"

success_rate=$((passed_checks * 100 / total_checks))

if [ $success_rate -ge 90 ]; then
    echo -e "状态: ${GREEN}✓ 健康 (${success_rate}%)${NC}"
    exit 0
elif [ $success_rate -ge 70 ]; then
    echo -e "状态: ${YELLOW}⚠ 部分异常 (${success_rate}%)${NC}"
    exit 1
else
    echo -e "状态: ${RED}✗ 严重问题 (${success_rate}%)${NC}"
    exit 2
fi
